<template>
  <div class="progress-view">
    <h1 class="text-2xl font-bold mb-6">学习进度</h1>
    
    <div v-if="loading" class="flex justify-center items-center py-8">
      <div class="spinner"></div>
    </div>
    
    <div v-else-if="error" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6">
      <p>{{ error }}</p>
    </div>
    
    <div v-else>
      <!-- 学习概览 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-xl font-semibold mb-4">学习概览</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="stat-card bg-blue-50 p-4 rounded-lg">
            <h3 class="text-lg font-medium text-blue-800">总卡片数</h3>
            <p class="text-3xl font-bold text-blue-600">{{ report.totalCards || 0 }}</p>
          </div>
          
          <div class="stat-card bg-green-50 p-4 rounded-lg">
            <h3 class="text-lg font-medium text-green-800">已完成卡片</h3>
            <p class="text-3xl font-bold text-green-600">{{ report.completedCards || 0 }}</p>
            <p class="text-sm text-green-700">
              完成率: {{ calculatePercentage(report.completedCards, report.totalCards) }}%
            </p>
          </div>
          
          <div class="stat-card bg-purple-50 p-4 rounded-lg">
            <h3 class="text-lg font-medium text-purple-800">平均掌握度</h3>
            <p class="text-3xl font-bold text-purple-600">{{ (report.averageConfidence || 0).toFixed(1) }}/5</p>
          </div>
        </div>
      </div>
      
      <!-- 练习统计 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-xl font-semibold mb-4">练习统计</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="stat-card bg-amber-50 p-4 rounded-lg">
            <h3 class="text-lg font-medium text-amber-800">总练习次数</h3>
            <p class="text-3xl font-bold text-amber-600">{{ report.totalExercises || 0 }}</p>
          </div>
          
          <div class="stat-card bg-emerald-50 p-4 rounded-lg">
            <h3 class="text-lg font-medium text-emerald-800">正确答题数</h3>
            <p class="text-3xl font-bold text-emerald-600">{{ report.correctExercises || 0 }}</p>
          </div>
          
          <div class="stat-card bg-teal-50 p-4 rounded-lg">
            <h3 class="text-lg font-medium text-teal-800">正确率</h3>
            <p class="text-3xl font-bold text-teal-600">{{ (report.accuracyRate || 0).toFixed(1) }}%</p>
          </div>
        </div>
      </div>
      
      <!-- 薄弱领域 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6" v-if="report.weakestAreas && report.weakestAreas.length > 0">
        <h2 class="text-xl font-semibold mb-4">需要加强的领域</h2>
        
        <div class="overflow-x-auto">
          <table class="min-w-full">
            <thead>
              <tr class="bg-gray-100">
                <th class="py-2 px-4 text-left">章节</th>
                <th class="py-2 px-4 text-left">错误率</th>
                <th class="py-2 px-4 text-left">练习次数</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(area, index) in report.weakestAreas" :key="index" class="border-b">
                <td class="py-2 px-4">{{ area.chapter }}</td>
                <td class="py-2 px-4">{{ area.errorRate.toFixed(1) }}%</td>
                <td class="py-2 px-4">{{ area.totalExercises }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- 最近活动 -->
      <div class="bg-white rounded-lg shadow-md p-6" v-if="report.recentActivity && report.recentActivity.length > 0">
        <h2 class="text-xl font-semibold mb-4">最近学习活动</h2>
        
        <div class="overflow-x-auto">
          <table class="min-w-full">
            <thead>
              <tr class="bg-gray-100">
                <th class="py-2 px-4 text-left">卡片</th>
                <th class="py-2 px-4 text-left">状态</th>
                <th class="py-2 px-4 text-left">掌握度</th>
                <th class="py-2 px-4 text-left">最后学习时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="activity in report.recentActivity" :key="activity._id" class="border-b">
                <td class="py-2 px-4">
                  <router-link 
                    v-if="activity.cardId" 
                    :to="`/cards/${activity.cardId._id}`" 
                    class="text-blue-600 hover:underline"
                  >
                    {{ activity.cardId.title || '未命名卡片' }}
                  </router-link>
                  <span v-else>卡片已删除</span>
                </td>
                <td class="py-2 px-4">
                  <span :class="getStatusClass(activity.status)">
                    {{ translateStatus(activity.status) }}
                  </span>
                </td>
                <td class="py-2 px-4">
                  <div class="flex items-center">
                    <div class="flex">
                      <span v-for="i in 5" :key="i" class="mr-1">
                        <i :class="i <= activity.confidence ? 'fas fa-star text-yellow-400' : 'far fa-star text-gray-300'"></i>
                      </span>
                    </div>
                    <span class="ml-2">{{ activity.confidence }}/5</span>
                  </div>
                </td>
                <td class="py-2 px-4">{{ formatDate(activity.lastViewed) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- 无数据提示 -->
      <div v-if="!hasData" class="bg-white rounded-lg shadow-md p-6 text-center">
        <i class="fas fa-chart-line text-gray-400 text-5xl mb-4"></i>
        <h3 class="text-xl font-medium text-gray-600 mb-2">暂无学习数据</h3>
        <p class="text-gray-500 mb-4">开始学习卡片和完成练习题，这里将显示您的学习进度</p>
        <router-link to="/documents" class="btn-primary">
          浏览学习资料
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/store/user';

export default {
  name: 'ProgressView',
  
  setup() {
    const userStore = useUserStore();
    const report = ref({});
    const loading = ref(false);
    const error = ref(null);
    
    // 计算是否有数据
    const hasData = computed(() => {
      return report.value && 
        (report.value.totalCards > 0 || 
         report.value.totalExercises > 0);
    });
    
    // 获取学习报告
    const fetchLearningReport = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const result = await userStore.fetchLearningReport();
        if (result.success) {
          report.value = result.report;
        } else {
          error.value = result.error;
        }
      } catch (err) {
        error.value = '获取学习报告失败';
        console.error('获取学习报告错误:', err);
      } finally {
        loading.value = false;
      }
    };
    
    // 计算百分比
    const calculatePercentage = (part, total) => {
      if (!total || total === 0) return 0;
      return Math.round((part / total) * 100);
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    // 获取状态对应的样式类
    const getStatusClass = (status) => {
      switch (status) {
        case 'completed':
          return 'text-green-600 font-medium';
        case 'in_progress':
          return 'text-blue-600 font-medium';
        case 'reviewing':
          return 'text-purple-600 font-medium';
        default:
          return 'text-gray-600';
      }
    };
    
    // 翻译状态文本
    const translateStatus = (status) => {
      const statusMap = {
        'not_started': '未开始',
        'in_progress': '学习中',
        'completed': '已完成',
        'reviewing': '复习中'
      };
      
      return statusMap[status] || status;
    };
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchLearningReport();
    });
    
    return {
      report,
      loading,
      error,
      hasData,
      calculatePercentage,
      formatDate,
      getStatusClass,
      translateStatus
    };
  }
};
</script>

<style scoped>
.progress-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 1.5rem;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-left-color: #3b82f6;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.btn-primary {
  display: inline-block;
  background-color: #3b82f6;
  color: white;
  font-weight: 500;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  transition: background-color 0.2s;
}

.btn-primary:hover {
  background-color: #2563eb;
}
</style> 